package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.*;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.GetIdUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PipedWriter;
import java.io.PrintWriter;
import java.util.*;

@Controller
@RequestMapping("/cargo/packing")
public class PackingController extends BaseController {

    //注入报运单service
    @Reference
    private ExportService exportService;

    //注入货物service
    @Reference
    private ContractProductService contractProductService;

    //注入购销合同service
    @Reference
    private ContractService contractService;

    //注入报运货物service
    @Reference
    private ExportProductService exportProductService;

    //注入装箱单service
    @Reference
    private PackingService packingService;


    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize){
        PackingExample packingExample = new PackingExample();
        PageInfo<Packing> pageInfo = packingService.findByPage(packingExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/packing/packing-list";
    }


    @Autowired
    private GetIdUtils getIdUtils;

        /**
         * 判断装箱的报运单的 装运港 目的港 收货人 是否一致
         */
    @RequestMapping("/toPacking")
    @ResponseBody
    public Map<String,Object> toPacking(String id) {
        Map<String,Object> map = new HashMap<>();
        //1、拿到报运单号
        String[] ids = getIdUtils.getId(id);
        //根据id查出报运单
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(ids));
        List<Export> exportList = exportService.findAll(exportExample);

       //判断装箱的报运单的 装运港 目的港 收货人 是否一致

        Export isExport = exportList.get(0);
        String shipmentPort = isExport.getShipmentPort();
        String destinationPort = isExport.getDestinationPort();
        String consignee = isExport.getConsignee();
        if (isExport.getState() != 2) {
            map.put("flag","false");
            map.put("message","未报运的单不能生成装箱单!");
            return map;
        }
        //多张报运单的情况下，遍历验证数据
        if (exportList.size() > 1) {
            for (int i = 1; i < exportList.size(); i++) {
                isExport = exportList.get(i);
                if (isExport.getState() != 2) {
                    map.put("flag", "false");
                    map.put("message", "未报运的单不能生成装箱单!");
                    return map;
                }
                if (!(shipmentPort.equals(isExport.getShipmentPort()) &&
                        destinationPort.equals(isExport.getDestinationPort()) &&
                        consignee.equals(isExport.getConsignee()))) {
                    map.put("flag", "false");
                    map.put("message", "装运港、目的港、收货人不一致!");
                    return map;
                }
            }
        }

        map.put("flag","true");
        return map;
    }

    /**
     *去到生成装箱单页面，并数据回显
     * @param id
     * @return
     */
    @RequestMapping("/toPackingForm")
    public String toPackingForm(String id) {
        request.setAttribute("id", id);
        //1、拿到报运单号
        String[] ids = id.split(",");
        //根据id查出报运单
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(Arrays.asList(ids));
        List<Export> exportList = exportService.findAll(exportExample);


        //创建一个装箱单对象
        Packing packing = new Packing();


        //定义合同号
        String exportNos = "";
        //定义总体积
        Double totalVolume = 0.0;
        //定义总毛重
        Double grossWeights = 0.0;
        //定义总净重
        Double netWeights = 0.0;
        //定义装箱费用
        Double packingMoney = 0.0;

        //遍历报运单
        for (Export export : exportList) {
            //找出报运单下的购销合同
            String[] contractIds = export.getContractIds().split(",");

            //合同号
            ContractExample contractExample = new ContractExample();
            contractExample.createCriteria().andIdIn(Arrays.asList(contractIds));
            List<Contract> contractList = contractService.findAll(contractExample);

            //遍历购销合同 获取合同号
            for (Contract contract : contractList) {
                exportNos += contract.getContractNo() + " ";
            }

            //根据报运单查出报运货物
            ExportProductExample exportProductExample = new ExportProductExample();
            exportProductExample.createCriteria().andExportIdEqualTo(export.getId());
            //找到该报运单下的所有货物
            List<ExportProduct> exportProductList = exportProductService.findAll(exportProductExample);

            //遍历货物补充数据
            for (ExportProduct exportProduct : exportProductList) {
                //总体积=每个货物的体积，货物体积=长*宽*高
                if (exportProduct.getSizeLength() != null && exportProduct.getSizeWidth() != null && exportProduct.getSizeHeight() != null) {
                    totalVolume += exportProduct.getSizeLength() * exportProduct.getSizeWidth() * exportProduct.getSizeHeight();
                }
                //总毛重=每个货物的毛重和
                if (exportProduct.getGrossWeight() != null) {
                    grossWeights += exportProduct.getGrossWeight();
                }
                //总净重=每个货物的净重
                if (exportProduct.getNetWeight() != null) {
                    netWeights += exportProduct.getNetWeight();
                }
            }
        }

        //装箱费用=总毛重*520
        packingMoney = grossWeights * 520;

        packing.setExportNos(exportNos);
        packing.setTotalVolume(totalVolume);
        packing.setGrossWeights(grossWeights);
        packing.setNetWeights(netWeights);
        packing.setPackingMoney(packingMoney);
        packing.setExportIds(id);

        request.setAttribute("packing",packing);

        return "cargo/packing/packing-toPacking";
    }


    /**
     * 新增装箱单或修改装箱单2
     * @param packing
     * @return
     */
    @RequestMapping("/edit")
    public String edit(Packing packing) {
        //如果装箱编号为空走新增，否则修改
        System.out.println();
        if (StringUtils.isEmpty(packing.getPackingListId())) {
            //新增
            packingService.save(packing);
        } else {
            //修改
            packingService.update(packing);
        }
        return "redirect:/cargo/packing/list.do";
    }


    /**
     * 判断是否可以删除
     */
    @RequestMapping("/ifDelete")
    @ResponseBody
    public void ifDelete(String id) throws IOException {
        PrintWriter out = response.getWriter();

        Packing packing = packingService.selectByPrimaryKey(id);
        if (packing.getState() == 0) {
            out.print("true");
        } else {
            out.print("false");
        }
    }
    /**
     * 删除装箱单
     * /cargo/export/delete.do?id=08426ad5-c6e4-47d0-89eb-a875e2023a73
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        packingService.deleteByPrimaryKey(id);
        return "redirect:/cargo/packing/list.do";
    }


    /**
     * 查看装箱单
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        Packing packing = packingService.selectByPrimaryKey(id);

        request.setAttribute("packing",packing);
        return "cargo/packing/packing-view";
    }

}
